package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.ACTION_MOVE
import android.view.MotionEvent.ACTION_UP
import android.view.View
import android.view.ViewGroup
import com.example.geoaimavlink_android.R
import com.geoai.mavlink.geoainet.base.mavlinkcore.engine.GEOAIError
import com.geoai.mavlink.geoainet.payload.enums.CameraNV3StreamSource
import com.geoai.mavlink.geoainet.payload.info.ThermalAreaMeasureInfo
import com.geoai.mavlink.geoainet.payload.info.ThermalSpotMeasureInfo
import com.geoai.mavlink.geoainet.payload.interfaces.INV3CameraListener
import com.geoai.mavlink.geoainet.payload.interfaces.IThermalAreaMeasureListener
import com.geoai.mavlink.geoainet.payload.interfaces.IThermalSpotMeasureListener
import com.geoai.video.VideoFeederView4
import com.geoai.video.YFVParams
import com.google.gson.Gson
import kotlinx.android.synthetic.main.frag_thermal.btnSwitchThermalMode
import kotlinx.android.synthetic.main.frag_thermal.btnThermalAreaMeasureEnable
import kotlinx.android.synthetic.main.frag_thermal.btnThermalPointMeasureEnable
import kotlinx.android.synthetic.main.frag_thermal.coverView
import kotlinx.android.synthetic.main.frag_thermal.tvAvg
import kotlinx.android.synthetic.main.frag_thermal.tvMax
import kotlinx.android.synthetic.main.frag_thermal.tvMin
import kotlinx.android.synthetic.main.frag_thermal.tvSpot
import kotlinx.android.synthetic.main.frag_thermal.videoFeeder

class ThermalMeasureFragment: BaseFragment() {

    private var measureType = MeasureType.NONE

    enum class MeasureType {
        SPOT,
        AREA,
        NONE
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_thermal, null)
    }

    private val spotMeasureListener: IThermalSpotMeasureListener = object : IThermalSpotMeasureListener{
        override fun onData(info: ThermalSpotMeasureInfo?) {
            info?.let { thermalSpotMeasureInfo ->
                val x = thermalSpotMeasureInfo.spot.x / 640.0f
                val y = thermalSpotMeasureInfo.spot.y / 512.0f

                if (coverView != null) coverView.setRedPoint(x, y)

                tvSpot?.visibility = View.VISIBLE

                tvAvg?.text = "AVG:${thermalSpotMeasureInfo.averageTemperature}"
                tvMax?.text = "MAX:${thermalSpotMeasureInfo.maxTemperature}"
                tvMin?.text = "MIN:${thermalSpotMeasureInfo.minTemperature}"
                tvSpot?.text = "SPOT:${thermalSpotMeasureInfo.spotTemperature}"
            }
        }

        override fun onResult(error: GEOAIError?) {
        }
    }

    private val areaMeasureListener: IThermalAreaMeasureListener = object : IThermalAreaMeasureListener{
        override fun onData(info: ThermalAreaMeasureInfo?) {
            info?.let { thermalAreaMeasureInfo ->
                val rx = thermalAreaMeasureInfo.maxSpot.x / 640.0f
                val ry = thermalAreaMeasureInfo.maxSpot.y / 512.0f

                val bx = thermalAreaMeasureInfo.minSpot.x / 640.0f
                val by = thermalAreaMeasureInfo.minSpot.y / 512.0f

                if (coverView != null) coverView.setRedPoint(rx, ry)
                if (coverView != null) coverView.setBluePoint(bx, by)

                tvSpot?.visibility = View.GONE

                tvAvg?.text = "AVG:${thermalAreaMeasureInfo.averageTemperature}"
                tvMax?.text = "MAX:${thermalAreaMeasureInfo.maxTemperature}"
                tvMin?.text = "MIN:${thermalAreaMeasureInfo.minTemperature}"
            }
        }

        override fun onResult(error: GEOAIError?) {
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initVideo()
        initAction()
        initListener()
    }

    private fun initListener() {
    }

    private fun initAction() {
        btnSwitchThermalMode.setOnClickListener {
            getProduct()?.payloadManager?.camera?.let {camera ->
                if (camera is INV3CameraListener) {
                    camera.setCameraSource(CameraNV3StreamSource.LIVEVIEW_CAMERA_SOURCE_IR, null)
                }
            }
        }
        btnThermalPointMeasureEnable.setOnClickListener {
            coverView.clear()
            measureType = MeasureType.SPOT
        }
        btnThermalAreaMeasureEnable.setOnClickListener {
            coverView.clear()
            measureType = MeasureType.AREA
        }
    }

    private fun initVideo() {
        videoFeeder.initPlayer(
            YFVParams.Builder()
                .setPlayNode(VideoFeederView4.PlayNode.MAIN_CAM)
                .setSurfaceMode(VideoFeederView4.SurfaceMode.SURFACE)
                .setVideoCodecMode(VideoFeederView4.CodecMode.HARDWARE)
                .setVideoDecodeMode(VideoFeederView4.DecodeMode.H265)
                .build(), VideoFeederView4::startPlayer)

        videoFeeder.setOnTouchListener { v, event ->
            if (measureType == MeasureType.SPOT) {
                when (event.action) {
                    ACTION_UP -> {
                        val xPercent = event.x / v.width
                        val yPercent = event.y / v.height
                        val xPoint: Int = (xPercent * 640).toInt()
                        val yPoint: Int = (yPercent * 512).toInt()
                        getProduct()?.payloadManager?.camera?.let { camera ->
                            if (camera is INV3CameraListener) {
                                camera.startSpotThermalMeasurement(xPoint, yPoint, spotMeasureListener)
                            }
                        }
                    }
                }
            }
            if (measureType == MeasureType.AREA) {
                when (event.action) {
                    ACTION_DOWN -> {
                        coverView.setStartX(event.x, event.y)
                    }
                    ACTION_MOVE -> {
                        coverView.setEndX(event.x, event.y)
                    }
                    ACTION_UP -> {
                        measureType = MeasureType.NONE

                        getProduct()?.payloadManager?.camera?.let { camera ->
                            if (camera is INV3CameraListener) {
                                val startX = ((coverView.areaStartX / v.width) * 640 ).toInt()
                                val endX = ((coverView.areaEndX / v.width) * 640 ).toInt()
                                val startY = ((coverView.areaStartY / v.height) * 512 ).toInt()
                                val endY = ((coverView.areaEndY / v.height) * 512 ).toInt()
                                camera.startAreaThermalMeasurement(startX, startY, endX - startX, endY - startY, areaMeasureListener)
                            }
                        }
                    }
                }
            }
            true
        }
    }

    override fun onDestroyView() {
        getProduct()?.payloadManager?.camera?.let { camera ->
            if (camera is INV3CameraListener) {
                camera.startSpotThermalMeasurement(0, 0, null)
                camera.startAreaThermalMeasurement(0, 0, 0, 0, null)
                camera.stopThermalMeasurement(null)
            }
        }
        super.onDestroyView()
    }
}